package algo.linkedlist.impl;

/**
 * @Title:
 * @Description:
 * @Author Fay Wang
 * @Date 2022/4/27 10:18
 * @Version 1.0
 */
public class LinkedListNor<E> {

    private class Node {
        private E data;
        private Node next;

        public Node(E data, Node next) {
            this.data = data;
            this.next = next;
        }

        public Node(E data) {
            this(data, null);
        }

        public Node() {
            this(null, null);
        }

        @Override
        public String toString() {
            return data.toString();
        }
    }

    private Node head;
    private int size;

    public LinkedListNor() {
        head = null;
        size = 0;
    }

    // 获取链表的元素个数
    public int getSize() {
        return size;
    }

    // 返回链表是否为空
    public boolean isEmpty() {
        return size == 0;
    }

    // 在链表index(0-based)位置添加新元素e
    // 练习用，非常用操作
    public void add(int index, E e) {
        if (index < 0 || index > size) {
            throw new IllegalArgumentException("Add failed. Illegal index.");
        }
        if (index == 0) {
            addFirst(e);
        }else{
            Node prev = head;
            for (int i = 0; i < index - 1; i++) {
                prev = prev.next;
                /**
                 * Node node = new Node(e);
                 * node.next = prev.next;
                 * prev.next = node;
                 */
                prev.next = new Node(e, prev.next);
                size++;
            }
        }
    }

    // 在链表头部添加新元素e
    public void addFirst(E e) {
        /**
         * Node node = new Node(e)
         * node.next = head;
         * head = node;
         */
        head = new Node(e, head);
        size ++;
    }

    // 在链表尾部添加新元素e
    public void addLast(E e) {
        add(size, e);
    }


}
